package com.aoip.telemetry.telemetry.core.crc;

import com.aoip.telemetry.telemetry.core.util.ConvertUtil;

/**
 * st开头报文crc校验工具类
 *
 * @author chenbai
 * @version 1.0
 * @date 2022/6/26 22:33
 */
public class SnStCrcUtil {
    public static void main(String[] args) {
        System.out.println(crc("ST 6071860J43 TT 06012115 PN05 0 RC 2930 Z01 27549 Z02 2 BV 130 SI1 31 DC 0 "));
    }

    public static String crc(String str) {
        char[] chars = str.toCharArray();
        int sum = 0x00;
        for (char item : chars) {
            String s = ConvertUtil.convertCharToHex(item).toUpperCase();
            int temp = Integer.parseInt(s, 16) + sum;
            sum = (temp) & 0xff;
//            System.out.println("s:" + s + "sum:" + sum + "--10进制sum：==" + temp);
        }
//        System.out.println(sum);
        //        取反
        sum = ~sum & 0xFF;
        // + 1 并舍弃进位
        sum = (sum + 0x01) & 0xFF;
//        System.out.println(sum);
//        0110 0110 拆分成两个字节，高4位 和低4位
        int high = sum << 4 & 0xF00;
        int low = sum & 0x0F;
        sum = high + low;
//        System.out.println(sum);
        sum = sum + 0x6161;
//        System.out.println(sum);
        return ConvertUtil.convertHexToString(Integer.toHexString(sum));
    }

}
